package com.example.utils.util;

import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * TODO     java提供的零拷贝方式
 *          Java NIO对mmap的支持
 *          Java NIO对sendfile的支持
 *
 * @ClassName MmapTest
 * @Author xiaojiang
 * @Date 2021/12/28 下午 14:20
 */
public class MmapTest {

    /**
     *  TODO     Java NIO有一个MappedByteBuffer的类，可以用来实现内存映射。
     *           它的底层是调用了Linux内核的mmap的API。
     *           mmap的小demo如下：
     * @Author 江
     * @Date 2021/12/28 下午 14:23
     */
    /*public static void main(String[] args) {
        try {
            FileChannel readChannel = FileChannel.open(Paths.get("./jay.txt"), StandardOpenOption.READ);
            MappedByteBuffer data = readChannel.map(FileChannel.MapMode.READ_ONLY, 0, 1024 * 1024 * 40);
            FileChannel writeChannel = FileChannel.open(Paths.get("./siting.txt"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
            //数据传输
            writeChannel.write(data);
            readChannel.close();
            writeChannel.close();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }*/

    /**
     *  TODO    FileChannel的transferTo()/transferFrom()，底层就是sendfile() 系统调用函数。
     *          sendfile的小demo如下：
     * @Author 江
     * @Date 2021/12/28 下午 14:25
     */
    public static void main(String[] args) {
        try {
            FileChannel readChannel = FileChannel.open(Paths.get("./jay.txt"), StandardOpenOption.READ);
            long len = readChannel.size();
            long position = readChannel.position();

            FileChannel writeChannel = FileChannel.open(Paths.get("./siting.txt"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
            //数据传输
            readChannel.transferTo(position, len, writeChannel);
            readChannel.close();
            writeChannel.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}
